// pages/selfAssessment/question/result.js
const api = require('../../../config/api')
const request = require('../../../utils/request')
const { getBarAndTitleHeight } = require('../../../utils/util')
const { saveImage } = require('../../../utils/photo')
const app = getApp()
let hadBack = false
let handleNext = false
Page({
  /**
   * 页面的初始数据
   */
  data: {
    result: {},
    questionInfo: '',
    questionResult: '',
    monthAge: '', // 当前年龄
    sceneList: [],
    isResultList: false,
    isTraining: false,
    ...getBarAndTitleHeight(true),
    trainingId: '',

    shareInfo: {}, // 分享数据
    hasNextData: {},
    showPoster: false,
    posterSrc:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend3112705936ec4679ad331a5d1cac2faf.png', // 海报图片
    // bottomHeight: app.kBottomSafeHeight + 22,
    mgB: 132 + app.kBottomSafeHeight,
    modalHeight: app.kBottomSafeHeight + 345,
    bottomHeight: app.kBottomSafeHeight + 43,
    stepHeight: app.kBottomSafeHeight + 266,
    showBottom: false,
    awardShow: false,// 活动领奖弹是否显示
    fromOrigin: 0,// 从活动训练还是普通训练进入
    activityId: '',// 从活动训练训练进入接收活动id
    posterImg: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zhiliao-applet/CmcFNMinKpDV8835b43bb6765ed5d0aaa8d699de15d4.png', // 海报图片
    codeImg: '', // 用户小程序码
    imagePath: '',
    canvasHeight: 0,
    canvasWidth: 0,
    canvasLeft: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    this.setData({
      isResultList: options?.isResultList,
      isTraining: options?.isTraining,
      ...getBarAndTitleHeight(),
      trainingId: options?.pathId,
      fromOrigin: Number(options?.fromOrigin) || 0,
      activityId: options?.activityId || '',
    })
    this.getResult(Number(options.id))
    this.getRecommendTraining()
    if (options?.isTraining) {
      app.globalData.resultBack = true
    }
    if (options?.pathId) {
      this.getShareInfo()
      if(options?.activityId){
        this.getAwardInfo()
        this.getQRCode()
      }
    }
  },
  savePhoto: function () {
		let that = this
		let {
			posterImg,
			codeImg
		} = that.data
		wx.downloadFile({
			url: posterImg,
			success(res) {
				console.log('downloadFile','sucess');
				const ctx = wx.createCanvasContext('myCanvas', that)
				wx.getImageInfo({
					src: posterImg,
					success: function (res) {
						// 绘制背景海报到canvas
						var sysInfo = wx.getSystemInfoSync()
						let windowWidth = sysInfo.windowWidth
						var scale = (windowWidth / 375) * 0.92 //不同屏幕下canvas的适配比例；设计稿是750宽
						let imgW = 274 * scale // 274
						let imgH = 407 * scale // 407
						let imgPath = res.path
						let codeSize = 80 * scale

						that.setData({
							canvasHeight: imgH,
							canvasWidth: imgW,
							canvasLeft: (windowWidth - imgW) / 2,
						})
						ctx.drawImage(imgPath, 0, 0, imgW, imgH)
						wx.getImageInfo({
							src: codeImg,
							success: function (res) {
								// 图片的x坐标
								let bg_x = (imgW - codeSize) / 2 // 10
								// 图片的y坐标
								let bg_y = imgH - codeSize - 35 // 70
								// 图片宽度
								let bg_w = codeSize
								// 图片高度
								let bg_h = codeSize
								// 图片圆角
								let bg_r = 6
								// 绘制海报背景图片圆角
								ctx.save()
								ctx.beginPath()
								ctx.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
								ctx.arc(bg_x + bg_w - bg_r,bg_y + bg_r,bg_r,Math.PI * 1.5,Math.PI * 2)
								ctx.arc(bg_x + bg_w - bg_r,bg_y + bg_h - bg_r,bg_r,0,Math.PI * 0.5)
								ctx.arc(bg_x + bg_r,bg_y + bg_h - bg_r,bg_r,Math.PI * 0.5,Math.PI)
								ctx.clip()
								ctx.drawImage(res.path, bg_x, bg_y, bg_w, bg_h)
								ctx.draw()
								setTimeout(() => {
									wx.canvasToTempFilePath({
											canvasId: 'myCanvas',
											success: function (res) {
												that.setData({
													imagePath: res.tempFilePath,
												})
											},
											fail: function (res) {},
										},
										this
									)
								}, 1000)
							},
						})
					},
				})
			},
		})
	},
	// 生成小程序码
	async getQRCode() {
		let {activityId} = this.data
		if(activityId){
			const res = await request.get(
				api.createQrcodeImg, {
					activityId: activityId,
				}, {
					loading: false
				}
			)
			if (res.httpStatus === 200) {
				this.setData({
					codeImg: res.data,
				})
				this.savePhoto()
			}
		}
	},
	// 保存海报
	handleSave() {
		wx.showLoading({
			title: '保存中...',
			mask: true
		})
		setTimeout(() => {
			wx.hideLoading()
			let {
				imagePath
			} = this.data
			saveImage(imagePath)
		}, 1500)
	},
  async getAwardInfo(){
    let { trainingId } = this.data
    const userId = wx.getStorageSync('userId')
    const res = await request.get(
      api.getUserActivityStatus,
      {
        userId,
        activityTrainingId: trainingId
      },
      { loading: false,message: false }
    )
    if (res.httpStatus === 200) {
      // isFillAddress--是否已填写收货信息，1 已填写 / 0 未填写
      // isMeetCondition--是否满足领奖条件，1 已满足 / 0 未满足
      if(res.data.isMeetCondition === 1 && res.data.isFillAddress === 0){
        this.setData({
          awardShow: true
        })
      }
    }
  },
  // 获取分享信息
  async getShareInfo() {
    let { trainingId } = this.data
    const res = await request.get(api.shareTrainInfo + trainingId,{},{loading: false})
    if (res.httpStatus === 200) {
      this.setData({
        shareInfo: res.data,
      })

      if (res.data.posterImageUrl) {
        this.setData({
          posterSrc: res.data.posterImageUrl,
        })
      }
    }
  },
  getResult: async function (recordId) {
    const res = await request.get(
      api.handResult + recordId,
      {},
      { loading: false }
    )
    const finishTaskEntrance = app.globalData.finishTaskEntrance
    if (res.httpStatus === 200) {
      let monthNumber = res.data.patientMonthAge
      let ageYear = Math.floor(monthNumber / 12)
      let ageMonth = monthNumber % 12

      this.setData({
        result: res.data,
        monthAge:
          ageYear < 1
            ? ageMonth + '月'
            : ageMonth === 0
            ? ageYear + '岁'
            : ageYear + '岁' + ageMonth + '月',
      })

      // 查询是否有下一题
      console.log('finishTaskEntrance', finishTaskEntrance)
      const { taskFlowId } = res.data
      if (finishTaskEntrance !== 4 && taskFlowId) {
        const hasNextRes = await request.get(api.getNextTask, {
          detailId: taskFlowId,
          getType: finishTaskEntrance == 2 ? 2 : 1,
        },{loading: false})
        console.log('hasNextRes', hasNextRes)
        if (hasNextRes.httpStatus) {
          this.setData({
            hasNextData: { ...hasNextRes.data },
            showBottom: res.data.origin==3 || isResultList !=='isResult'&&res.data.origin!==3
          })
        }
      }
    }
  },
  // 去下一项任务
  toNextTask() {
    const { detailId, questionnaireId, trainingId, trainingType } =
      this.data.hasNextData
    handleNext = true
    app.globalData.isHandleNext = 1
    let { fromOrigin, activityId } = this.data
    if (trainingType === 1) {
      wx.redirectTo({
        url: `/pages/sceneTaskDetail/index?id=${detailId}&fromOrigin=${fromOrigin}&activityId=${activityId}`,
      })
    } else {
      wx.redirectTo({
        url: `/pages/selfAssessment/question/index?key=1&pathId=${trainingId}&id=${questionnaireId}&taskFlowId=${detailId}&fromOrigin=${fromOrigin}&activityId=${activityId}`,
      })
    }
  },
  // 推荐训练列表
  async getRecommendTraining() {
    const res = await request.get(api.recommendTraining, {}, { loading: false })
    if (res.httpStatus === 200) {
      this.setData({
        sceneList: res.data,
      })
    }
  },
  // 点击跳转训练任务详情
  handleSceneTrainDetail(e) {
    let trainingId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/sceneTrainDetail/index?trainingId=' + trainingId,
    })
  },
  back() {
    const pages = getCurrentPages()

    console.log('pages----', pages)

    if (handleNext) {
      return
    }
    if (hadBack) {
      return
    }
    hadBack = true
    const { isResultList, isTraining, trainingId } = this.data
    if (isResultList !== 'isResult') {
      if (isTraining) {
        wx.setStorageSync('trainingId', trainingId)
        app.handleFinishTaskBack()
      } else {
        wx.switchTab({
          url: `/pages/index/index`,
        })
      }
    } else {
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  // 显示分享弹窗
  showShareSheet() {
    this.setData({
      showPoster: true,
    })
    this.shareSheet.show()
  },
  // 隐藏分享弹窗
  hideShareSheet() {
    this.setData({
      showPoster: false,
    })
    this.shareSheet.hide()
  },
  // 保存图片到相册
  savePic: function () {
    let that = this
    let { posterSrc, activityId } = this.data
    if(activityId){
      that.handleSave()
      return
    }
    wx.getImageInfo({
      src: posterSrc,
      success: function (sres) {
        wx.saveImageToPhotosAlbum({
          filePath: sres.path,
          success: function (fres) {
            that.hideShareSheet()
            wx.showToast({
              title: '保存成功',
              icon: 'success',
            })
          },
          fail: function (fres) {
            wx.showToast({
              title: '保存失败',
              icon: 'error',
            })
          },
        })
      },
    })
  },
  // 领奖弹窗点击“再等等”
  handleCancle(){
    this.setData({
      awardShow: false
    })
  },
  // 领奖弹窗点击“去领奖”
  handleAward(){
    this.setData({
      awardShow: false
    })

     // 返回活动页面
     const pages = getCurrentPages()
     pages.forEach((item, index) => {
       if (item.route.indexOf('activity/practiceAward/index') !== -1) {
         wx.navigateBack({
           delta: pages.length - 2 - index,
         })
         return
       }
     })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.shareSheet = this.selectComponent('#shareSheet')
    if(this.shareSheet){
      this.shareSheet.hide()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const patientInfo = wx.getStorageSync('patientInfo')
    this.getPatientDetial(patientInfo)
    hadBack = false
    handleNext = false
  },
  // 获取患者列表
  getPatientDetial: async function (patientInfo) {
    let birthday = patientInfo.birthday.substring(0, 10)
    // let ageStr = calculateAge(birthday);
    let target = patientInfo
    // let ageObj = { age: ageStr };
    // target = Object.assign(target, ageObj);
    this.setData({
      patientInfo: target,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (app.globalData.finishTaskEntrance === 4 || app.globalData.finishTaskEntrance === 5) {
      return
    }
    if (handleNext) {
      return
    }
    let resultBack = app.globalData.resultBack
    if (resultBack) {
      wx.disableAlertBeforeUnload({
        success: (res) => {
          app.globalData.resultBack = false
        },
      })
    }
    setTimeout(() => {
      if (hadBack) {
        return
      }
      hadBack = true
      const { isResultList, isTraining, trainingId } = this.data
      console.log('isTraining---', isTraining)
      if (isResultList !== 'isResult') {
        if (isTraining) {
          wx.setStorageSync('trainingId', trainingId)
          app.handleFinishTaskBack()
        } else {
          wx.switchTab({
            url: `/pages/index/index`,
          })
        }
      }
    }, 300)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { shareInfo, trainingId, fromOrigin, activityId } = this.data
    if(fromOrigin === 1){
      const userId = wx.getStorageSync('userId')
      return {
        title: '可知成长邀您领实物好礼，包邮到家',
        path: `/pages/index/index?fromShare=practiceAward&activityId=${activityId}&userId=${userId}`,
        imageUrl:
          'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend7ac3684b69484eaebe33de50ddaebc04.png',
      }
    }
    return {
      title: shareInfo.trainingName,
      path: '/pages/sceneTrainDetail/index?trainingId=' + trainingId,
      imageUrl:
        shareInfo.shareImageUrl ||
        'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend5d6c29cf96f348d08c6a56d83a995686.png',
    }
  },
})
